/**
 * 
 */
package cn.springsoter.core.tool.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang3.StringUtils;

import cn.springsoter.core.tool.enums.MessageDigestAlgorithmsEnum;

/**
 * 文本摘要加密工具类
 * 
 * @author kevin
 *
 */
public class MessageDigestUtil {
	
	private MessageDigestUtil() {
	}
	
	/**
	 * 对文本摘要加密
	 * 
	 * @param plainText		要加密的明文文本
	 * @param messageDigestAlgorithmsEnum	加密算法枚举，参考枚举类：MessageDigestAlgorithmsEnum.java
	 * @return	返回小写的加密串
	 */
    public static String messageDigest(String plainText, MessageDigestAlgorithmsEnum messageDigestAlgorithmsEnum) {
        if (StringUtils.isBlank(plainText)) {
            return null;
        }
        String mdStr = null;
        try {
            MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithmsEnum.getValue());
            md.update(plainText.getBytes(StandardCharsets.UTF_8));
            byte[] b = md.digest();
            int i;
            StringBuilder builder = new StringBuilder(32);
            for (byte value : b) {
                i = value;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    builder.append("0");
                }
                builder.append(Integer.toHexString(i));
            }
            mdStr = builder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return mdStr;
    }
}
